﻿using System;
using System.Web.Mvc;
using Nop.Plugin.Widgets.ScrollTop.Models;
using Nop.Services.Configuration;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework;
using Nop.Services.Media;
using System.IO;
using System.Web.Hosting;
using Nop.Services.Localization;

namespace Nop.Plugin.Widgets.ScrollTop.Controllers
{
    public class WidgetsScrollTopController : BasePluginController
    {
        #region Fields
        private readonly ISettingService _settingService;
        private readonly ScrollTopSettings _ScrollTopSettings;
        private readonly IPictureService _pictureService;
        private readonly ILocalizationService _localizationService;

        protected virtual string MapPath(string path)
        {
            if (HostingEnvironment.IsHosted)
            {
                //hosted
                return HostingEnvironment.MapPath(path);
            }
            else
            {
                //not hosted. For example, run in unit tests
                string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                path = path.Replace("~/", "").TrimStart('/').Replace('/', '\\');
                return Path.Combine(baseDirectory, path);
            }
        }
        #endregion

        #region Constructors

        public WidgetsScrollTopController(ISettingService settingService,
            ScrollTopSettings ScrollTopSettings, IPictureService pictureService,
                ILocalizationService localizationService)
        {
            this._settingService = settingService;
            this._ScrollTopSettings = ScrollTopSettings;
            this._pictureService = pictureService;
            this._localizationService = localizationService;
        }

        #endregion

        #region Utilities
        
        [NonAction]
        public virtual void SaveCssfile(ScrollTopSettings settings)
        {
            if (settings == null)
                throw new ArgumentNullException("settings");

            //use webHelper.MapPath instead of HostingEnvironment.MapPath which is not available in unit tests
            string filePath = Path.Combine(MapPath("~/Plugins/Widgets.ScrollTop/Content/"), "style.css");
            if (! System.IO.File.Exists(filePath))
            {
                using (System.IO.File.Create(filePath))
                {
                    //we use 'using' to close the file after it's created
                }
            }

            var text = ComposeCssFile(settings);
            System.IO.File.WriteAllText(filePath, text);
        }

        private string ComposeCssFile(ScrollTopSettings settings)
        {
            var pictureUrl = _pictureService.GetPictureUrl(settings.PictureId, targetSize: ((settings.Width==0)? 51 : settings.Width), showDefaultPicture: false);

            string strAll = ".go-top {text-decoration: none; ";
            strAll += "position: fixed; bottom: 2em; ";
            strAll += settings.ButtonPosition.ToString() + ": 2em; ";

            if (!string.IsNullOrEmpty(pictureUrl))
            {
                strAll += "width: " + ((settings.Width == 0) ? 51 : settings.Width) + "px; ";
                strAll += "height: " + ((settings.Height == 0) ? 51 : settings.Height) + "px; ";
                strAll += "background: url('" + pictureUrl + "') no-repeat;";
                strAll += "display: none;}";
            }
            return strAll;
        }
        #endregion

        [AdminAuthorize]
        [ChildActionOnly]
        public ActionResult Configure()
        {
            var model = new ConfigurationModel();
            model.PositionId = Convert.ToInt32(_ScrollTopSettings.ButtonPosition);
            model.PositionValues = _ScrollTopSettings.ButtonPosition.ToSelectList();
            model.PictureId = _ScrollTopSettings.PictureId;
            model.PictureHeight = _ScrollTopSettings.Height;
            model.PictureWidth = _ScrollTopSettings.Width;

            return View("~/Plugins/Widgets.ScrollTop/Views/Configure.cshtml", model);
        }

        [HttpPost]
        [AdminAuthorize]
        [ChildActionOnly]
        public ActionResult Configure(ConfigurationModel model)
        {
            if (!ModelState.IsValid)
                return Configure();

            //save settings
            _ScrollTopSettings.ButtonPosition = (Positions) model.PositionId;
            _ScrollTopSettings.PictureId = model.PictureId;
            _ScrollTopSettings.Height = model.PictureHeight;
            _ScrollTopSettings.Width = model.PictureWidth;
       
            _settingService.SaveSetting(_ScrollTopSettings);
            
            //create css file
            SaveCssfile(_ScrollTopSettings);

            SuccessNotification(_localizationService.GetResource("Admin.Plugins.Saved"));
            return Configure();
        }

        [ChildActionOnly]
        public ActionResult PublicInfo(string widgetZone)
        {
            var model = new PublicInfoModel();
            model.PictureUrl = _pictureService.GetPictureUrl(_ScrollTopSettings.PictureId,targetSize:52, showDefaultPicture: false);

            return View("~/Plugins/Widgets.ScrollTop/Views/PublicInfo.cshtml", model);
        }
    }
}